package net.xdclass.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zhaowei
 * @Description TODO
 * @Remark 有问题直接联系我
 * @Version 1.0
 **/
public class JdkProxy implements InvocationHandler {

    /**
     * 定义目标类
     */
    private Object targetObject;


    /**
     * 获取代理对象
     */
    public Object getProxyInstance(Object targetObject){
        this.targetObject = targetObject;

        //通过反射创建代理对象
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
                targetObject.getClass().getInterfaces(),
                this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        openTransaction();
        Object result = method.invoke(targetObject, args);
        commitTransaction();
        return result;
    }



    public static void openTransaction(){
        System.out.println("开启事务");
    }

    public static void commitTransaction(){
        System.out.println("提交事务");
    }
}

